package com.ldl.exam.controllerBack;

import com.ldl.exam.constant.Constants;
import com.ldl.exam.entity.User;
import com.ldl.exam.exception.ExamException;
import com.ldl.exam.service.UserService;
import com.ldl.exam.util.AjaxResult;
import com.ldl.exam.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @author liudaolin
 * @version 1.0
 * @date 2022/10/02 21:11:46
 */
@RestController
@RequestMapping("/back/user")
public class UserController {
    @Autowired
    private UserService userService;
    // 登录
    @RequestMapping("/login")
    public AjaxResult login(String loginName, String pwd, HttpSession session) {
        if(CommonUtil.isEmpty(loginName)) {
            throw new ExamException("登录名不能为空");
        }
        if(CommonUtil.isEmpty(pwd)) {
            throw new ExamException("密码不能为空");
        }

        User login = userService.login(loginName, pwd);
        login.setPwd(CommonUtil.randomUUID());// 作为随机 token
        session.setAttribute(Constants.USER_LOGIN_KEY, login);
        return AjaxResult.isOk("登录成功", login);
    }

    // 退出
    @RequestMapping("/logout")
    public AjaxResult logout(HttpSession session) {
        session.invalidate();
        return AjaxResult.isOk("成功退出");
    }

    public AjaxResult modifyInfo(String name, String oldPwd, String newPwd, String rePwd) {
        // 修改自己的信息
        return null;
    }

    public AjaxResult modifyRole(Integer role) {
        // 只有 admin 才能修改 用户 role
        return null;
    }

    @RequestMapping("/resetPwd")
    public AjaxResult resetUserOrStuPwd(Integer userId, Integer stuId) {
        // 只有 admin 才能 重置 用户/学生 密码
        userService.resetPwd(userId, stuId);

        return AjaxResult.isOk("密码已重置为[ " + Constants.DEFAULT_PWD + " ]");
    }
}
